﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;

namespace VWise_DAO
{
  public static class CLogProcessor
  {
    public const int W_LOG_DEBUG = 3;
    public const int W_LOG_INFO = 2;
    public const int W_LOG_ERROR = 1;
    public const int W_LOG_NOTHING = 0;

    static string szLogLine;
    static StreamWriter sw = null;
    static string szlogName;
    static bool bLogOpened = false;
    static int iLogLevel = W_LOG_INFO;

    public static string szLogName
    {
      set
      {
        if (bLogOpened)
        {
          LogInfo(W_LOG_ERROR,"Can't change name of log file after initialized");
          return;
        }

        szlogName = value;
      }

      get
      {
        return szlogName;
      }
    }

    public static void InitLog()
    {
      string szLogLevel;
      try
      {
        szlogName = ConfigurationSettings.AppSettings["LogInternalName"] + "_" + string.Format("{0:yyyyMMdd}.log", DateTime.Now);
        szLogLevel = ConfigurationSettings.AppSettings["LogLevel"];
        
        if(!int.TryParse(szLogLevel ,out iLogLevel))
          iLogLevel = W_LOG_INFO;

        sw = new StreamWriter(szlogName, true);
        bLogOpened = true;
      }
      catch (Exception ex)
      {
        //Console.WriteLine("Can't open logfile:" + ex.ToString());
      }

      LogInfo(W_LOG_INFO,"CLogProcessor Started");
    }

    public static void CloseLog()
    {
      try
      {
        if (bLogOpened)
          sw.Close();
      }
      catch (Exception ex)
      {
        //Console.WriteLine("Can't close logfile:" + ex.ToString());
      }

      bLogOpened = false;
      sw = null;
    }


    public static void LogInfo(int iLogLevelLine, string szInfoLine)
    {
      szLogLine = string.Format("[{0:yyyy.MM.dd hh.mm.ss}]", DateTime.Now);

      if (iLogLevelLine > iLogLevel)
        return;

      switch (iLogLevelLine)
      {
        case W_LOG_DEBUG:
          szLogLine += " [DEBUG] ";
          break;

        case W_LOG_INFO:
          szLogLine += " [INFO ] ";
          break;
        
        case W_LOG_ERROR:
          szLogLine += " [ERROR] ";
          break;
      }
      
      szLogLine += szInfoLine;
      
      if (sw != null && bLogOpened)
      {
        //Console.WriteLine(szLogLine);
        sw.WriteLine(szLogLine);
        sw.Flush();
      }
    }
  }
}
